<template>
  <div class="common-container" style="min-height: calc(100vh - 60px)">
    <div class="common-content">
      <!-- 搜索和筛选 -->
      <div class="search-filter-container">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable style="width: 200px"></el-input>
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="searchForm.categoryId" placeholder="请选择分类" style="width: 120px">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品列表 -->
      <div class="goods-grid">
        <div v-for="goods in goodsList" :key="goods.id" class="goods-item">
          <div class="goods-img">
            <img :src="goods.img" :alt="goods.goodsName" @click="viewGoodsDetail(goods.id)">
          </div>
          <div class="goods-info">
            <div class="goods-name" @click="viewGoodsDetail(goods.id)">{{ goods.goodsName }}</div>
            <div class="goods-price">¥{{ goods.price }}</div>
            <div class="goods-actions">
              <el-button type="primary" size="small" @click.stop="addToCart(goods)">加入购物车</el-button>
              <el-button size="small" @click.stop="toggleCollect(goods)">
                <i v-if="goods.isCollect" class="el-icon-star-on" style="color: #ffd04b"></i>
                <i v-else class="el-icon-star-off"></i>
                收藏
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="goodsList.length === 0" class="empty-state">
        <el-empty description="暂无商品"></el-empty>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[12, 24, 48, 96]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 添加购物车成功提示 -->
    <el-tooltip ref="addCartTooltip" placement="top" content="已加入购物车" effect="light">
      <div></div>
    </el-tooltip>
  </div>
</template>

<script>
export default {
  name: "GoodsList",
  data() {
    return {
      goodsList: [],
      categoryList: [],
      searchForm: {
        name: '',
        categoryId: ''
      },
      currentPage: 1,
      pageSize: 12,
      total: 0
    };
  },
  created() {
    this.loadGoodsList();
    this.loadCategoryList();
  },
  methods: {
    loadGoodsList() {
      this.request.get("/goods/front/page", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          goodsName: this.searchForm.name,
          cateId: this.searchForm.categoryId
        }
      }).then(res => {
        if (res.code === 200) {
          // 直接使用后端返回的数据，不做字段映射
          this.goodsList = res.data.records || [];
          this.total = res.data.total || 0;
          // 加载用户的收藏状态
          this.loadUserCollects();
        } else {
          this.$message.error(res.msg || '获取商品列表失败');
        }
      }).catch(() => {
        this.$message.error('获取商品列表失败');
      });
    },
    
    loadCategoryList() {
      this.request.get("/cate").then(res => {
        if (res.code === 200) {
          this.categoryList = (res.data || []).map(item => ({
            id: item.id,
            name: item.cateName
          }));
        }
      });
    },
    
    loadUserCollects() {
      const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
      if (user) {
        this.request.get("/collect/page").then(res => {
          if (res.code === 200) {
            // 从收藏列表中提取商品ID
            const collectGoodsIds = (res.data.records || []).map(fav => fav.goodsId);
            this.goodsList.forEach(goods => {
              goods.isCollect = collectGoodsIds.includes(goods.id);
            });
          }
        });
      }
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.loadGoodsList();
    },
    
    viewGoodsDetail(goodsId) {
      this.$router.push(`/front/goodsDetail/${goodsId}`);
    },
    
    addToCart(goods) {
      const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
      if (!user) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      
      // 使用与后端统一的购物车接口
      this.request.post("/cart", {
        userId: user.id,
        goodsId: goods.id,
        goodsName: goods.goodsName,
        price: goods.price,
        num: 1,
        total: goods.price * 1
      }).then(res => {
        if (res.code === 200) {
          this.$message.success('已加入购物车');
        } else {
          this.$message.error(res.msg || '添加购物车失败');
        }
      }).catch(() => {
        this.$message.error('添加购物车失败');
      });
    },
    
    toggleCollect(goods) {
      const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
      if (!user) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      
      if (goods.isCollect) {
        // 取消收藏：先获取收藏ID，然后删除
        this.request.get("/collect/page").then(res => {
          if (res.code === 200) {
            const collectItem = (res.data.records || []).find(item => item.goodsId === goods.id);
            if (collectItem) {
              this.request.delete(`/collect/${collectItem.id}`).then(deleteRes => {
                if (deleteRes.code === 200) {
                  goods.isCollect = false;
                  this.$message.success('已取消收藏');
                }
              });
            }
          }
        });
      } else {
        // 添加收藏
        this.request.post("/collect", {
          goodsId: goods.id
        }).then(res => {
          if (res.code === 200) {
            goods.isCollect = true;
            this.$message.success('已收藏');
          } else {
            this.$message.error(res.msg || '收藏失败');
          }
        }).catch(() => {
          this.$message.error('收藏失败');
        });
      }
    },
    
    handleSizeChange(size) {
      this.pageSize = size;
      this.loadGoodsList();
    },
    
    handleCurrentChange(current) {
      this.currentPage = current;
      this.loadGoodsList();
    }
  }
};
</script>

<style scoped>
.common-container {
  padding: 0;
}

.common-content {
  margin-bottom: 20px;
}

.search-filter-container {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.demo-form-inline {
  display: flex;
  align-items: center;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.goods-item {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.goods-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.goods-img {
  text-align: center;
  margin-bottom: 15px;
  cursor: pointer;
}

.goods-img img {
  width: 200px;
  height: 200px;
  object-fit: contain;
}

.goods-info {
  text-align: center;
}

.goods-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 15px;
}

.goods-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  background-color: #fff;
  border-radius: 4px;
}
</style>